package com.itheima.dao.impl;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * 账户的持久层实现类
 */
public class UserDaoImpl implements IUserDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<User> findAllUser() {
        try {
            return runner.query("select * from user",new BeanListHandler<User>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public User findUserById(Integer userid) {
        try {
            return runner.query("select * from user where id = ?",new BeanHandler<User>(User.class),userid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void saveUser(User user) {
        try {
            runner.update("insert into user(username,password) values(?,?)",user.getUsername(),user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public void updateUser(User user) {
        try {
            runner.update("update user set username = ?,password = ? where id = ?",user.getUsername(),user.getPassword(),user.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteUser(Integer userid) {
        try {
            runner.update("delete from user where id = ?",userid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
